package cn.zjk.springframework.core.io;

import cn.hutool.core.lang.Assert;
import cn.zjk.springframework.util.ClassUtils;

import java.io.FileNotFoundException;
import java.io.InputStream;

/**
 * @description: classpath方式
 * @Author zjk
 * @className: ClassPathResource
 * @date: 2023/3/23 17:24
 */
public class ClassPathResource implements Resource{
    private final String path;
    private ClassLoader classLoader;

    public ClassPathResource(String path) {
        this(path,(ClassLoader) null);
    }

    public ClassPathResource(String path, ClassLoader classLoader) {
        Assert.notNull(path, "Path must not be null");
        this.path = path;
        this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader());
    }

    @Override
    public InputStream getInputStream() throws Exception {
        InputStream is = classLoader.getResourceAsStream(path);
        if(is == null){
            throw new FileNotFoundException(
                    this.path+"cannot open because it does not exist");
        }
        return is;
    }
}
